package com.fxsh168.server.fragments;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.fxsh168.server.activity.LoginActivity;
import com.fxsh168.server.activity.NearOrdersActivity;
import com.fxsh168.server.activity.PushOrders;
import com.fxsh168.server.base.BaseFragment;
import com.fxsh168.server.R;
import com.fxsh168.server.entitys.CarStatusEntity;
import com.fxsh168.server.entitys.PerSonInfo;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.entitys.PushOrdersEntity;
import com.fxsh168.server.entitys.RegiYZMCG;
import com.fxsh168.server.maps.MyOrientationListener;
import com.fxsh168.server.maps.NavQian;
import com.fxsh168.server.services.QueryDistanceService;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static android.content.Context.MODE_PRIVATE;

public class MapFragment extends BaseFragment implements OnClickListener {
    //判断是否有订单进行
    private boolean isDingDanJX = false;
    private MapView mMapView;
    private BaiduMap mBaiduMap;

    //定位相关
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private boolean isFirstIn = true;
    //记录下当前定位的经纬度
    private double mLatitude, mLongitude;
    //自定义定位图标
    //记录当前的位置
    private String mPhoneMap, tokenMap, routes;
    private PushOrdersEntity pushOrdersEntity;
    private List<PushOrdersEntity.DataBean> datajj = new ArrayList<>();
    private ArrayList<String> idjjs = new ArrayList<>();
    //    关于订单的
    LinearLayout liQiangOrder;
    TextView teHavingOrders, mQiangDan, mStartPlace, mEndPlace;
    ImageView imaCancel, imDingWei;
    TextView mOrderChi, teNearOrder;
    MyOrientationListener myOrientationListener;
    int mXDirection;   // 方向
    TextView stateCar;
    String carStat;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        SDKInitializer.initialize(MapFragment.this.getActivity().getApplication());
        return inflater.inflate(R.layout.fragment_map, container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        liQiangOrder = (LinearLayout) view.findViewById(R.id.liQiangDan);
        teHavingOrders = (TextView) view.findViewById(R.id.teHavingOrder);
        imaCancel = (ImageView) view.findViewById(R.id.imaCancel);
        mQiangDan = (TextView) view.findViewById(R.id.mQiangDan);
        mStartPlace = (TextView) view.findViewById(R.id.teStartPlace);
        mEndPlace = (TextView) view.findViewById(R.id.teEndPlace);
        mOrderChi = (TextView) view.findViewById(R.id.mOrderChi);
        imDingWei = (ImageView) view.findViewById(R.id.imDingWei);
        teNearOrder = (TextView) view.findViewById(R.id.teNearOrder);
        stateCar = (TextView) view.findViewById(R.id.stateCar);

        SharedPreferences sp = getActivity().getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        mPhoneMap = sp.getString("mPhone", "");
        tokenMap = sp.getString("token", "");
        myOrientationListener = new MyOrientationListener(MapFragment.this.getActivity().getApplication());
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                int dt = (int) x;  //h获取到方向信息
                mXDirection = 360 - dt;
            }
        });

        //初始化基础地图
        mMapView = (MapView) view.findViewById(R.id.id_bmapView);
        mMapView.showZoomControls(false);         //隐藏缩放按钮
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mLocationClient = new LocationClient(MapFragment.this.getActivity().getApplication());
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        //设置定位请求
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//定位模式为高精度
        option.setCoorType("bd09ll");//设置模式为bd09ll
        option.setIsNeedAddress(true);//需要定位位置
        option.setOpenGps(true); //打开gps
        option.setScanSpan(2000); //间隔定位时间
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        //设置精度为500米左右
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        //初始化定位
        initLocation();
        imDingWei.setOnClickListener(this);
        //附近订单
        teNearOrder.setOnClickListener(this);
        if (!TextUtils.isEmpty(mPhoneMap)) {
            stateCar();
        }
        stateCar.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imDingWei:
                initLocation();
                break;
            case R.id.teNearOrder:
                if (carStat == null || carStat.equals("0")){
                    Toast.makeText(getActivity(),"您还未出车",Toast.LENGTH_SHORT).show();
                    return;
                }
                initLocation();
                Intent inten2 = new Intent(MapFragment.this.getActivity(), NearOrdersActivity.class);
                inten2.putExtra("log", mLongitude);
                inten2.putExtra("lat", mLatitude);
                if (!TextUtils.isEmpty(tokenMap)) {
                    startActivity(inten2);
                }
                break;
            case R.id.stateCar:
                if (!TextUtils.isEmpty(mPhoneMap)) {
                    if (carStat != null && carStat.equals("1")) {
                        sendCar("0");
                    } else if (carStat != null && carStat.equals("0")) {
                        sendCar("1");
                    }
                } else {
                    jumpActivity(LoginActivity.class);
                    getActivity().finish();
                }
                break;
        }
    }

    //司机实时传送经纬度
    public void sendDriver() {
        OkHttpUtils.post().addParams("phone", mPhoneMap).addParams("dlat", mLatitude + "").addParams("dlng", mLongitude + "")
                .addParams("direction", mXDirection + "").url(Constant.SENDDRIVER).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("tag", mLatitude + "@" + mLongitude + "方向" + mXDirection + "实时经纬度发送" + response);
                    }
                });
    }

    //   首发车
    private void sendCar(final String statecar) {
        OkHttpUtils.post().addParams("phone", mPhoneMap).addParams("type", statecar).url(Constant.CLOSECAR)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("tagc", "收出车结果失败" + e);
            }

            @Override
            public void onResponse(String response, int id) {
                stateCar();
                PerSonInfo perSonInfo = new Gson().fromJson(response, PerSonInfo.class);
                String code = perSonInfo.getCode();
                if (code.equals("200")) {
                    if (statecar.equals("0")) {
                        showToast("收车成功");
                    } else if (statecar.equals("1")) {
                        showToast("出车成功");
                    }
                } else if (code.equals("201")) {
                    showToast("请求失败");
                }
            }
        });
    }

    //    获取出车状态
    private void stateCar() {
        OkHttpUtils.post().addParams("phone", mPhoneMap).url(Constant.STATEQUERY)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("tagc", "出车状态获取失败" + e);
            }

            @Override
            public void onResponse(String response, int id) {
                CarStatusEntity carStatus = new Gson().fromJson(response, CarStatusEntity.class);
                String code = carStatus.getCode();
                if (code.equals("200")) {
                    CarStatusEntity.DataBean data = carStatus.getData();
                    carStat = data.getStatus();
                    if (carStat.equals("1")) {
                        stateCar.setText("收车");
                    } else {
                        stateCar.setText("出车");
                    }
                }
            }
        });
    }


    public void initLocation() {
        mLocationClient.start();
        //设置进页面的时候就定位到自己位置
        LatLng latLng = new LatLng(mLatitude, mLongitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(msu);
    }


    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            MyLocationData data = new MyLocationData.Builder()
                    .accuracy(0)//精度
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(data);
            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            sendDriver();

            Log.e("tag", "司机经纬度打印" + mLatitude + "分割" + mLongitude + "token" + tokenMap);
            handlerGetOrder.sendEmptyMessage(200);
            if (isFirstIn) {
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(msu);
                isFirstIn = false;
            }
        }
    }


    private Handler handlerGetOrder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isDingDanJX) {
                if (carStat != null && carStat.equals("1")) {
                    getOrderInfo();     //   获取订单
                }
            }
        }
    };


    //   获取订单
    public void getOrderInfo() {
        OkHttpUtils.post().addParams("lat", mLatitude + "").addParams("lng", mLongitude + "")
                .addParams("phone", mPhoneMap).addParams("token", tokenMap).url(Constant.ORDERREQUEST)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    Log.e("tag", "地图界面数据获取" + response + "结束");
                    pushOrdersEntity = new Gson().fromJson(response, PushOrdersEntity.class);
                    datajj = pushOrdersEntity.getData();
                    String code = pushOrdersEntity.getCode().trim();
                    int codes = Integer.parseInt(code);
                    switch (codes) {
                        case 200:
                            handlerGetOrder.removeCallbacksAndMessages(null);
                            isDingDanJX = true;
                            routes = datajj.get(0).getRoutes().toString().trim();
                            int rid = Integer.parseInt(routes);
                            switch (rid) {
                                case 2://大巴
                                    //线路二，有订单，已接受
                                    teHavingOrders.setVisibility(View.VISIBLE);
                                    teHavingOrders.setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Intent inten = new Intent(MapFragment.this.getContext(), PushOrders.class);
                                            inten.putExtra("mLatitude", mLatitude);
                                            inten.putExtra("mLongitude", mLongitude);
                                            inten.putExtra("isDingDanJX", isDingDanJX);
                                            inten.putExtra("pushOrdersEntity", pushOrdersEntity);
                                            inten.setAction("dingdanxianlu2");
                                            isDingDanJX = true;
                                            //让对话框消失
                                            teHavingOrders.setVisibility(View.GONE);
                                            startActivity(inten);
                                        }
                                    });
                                    isDingDanJX = true;
                                    break;
                                case 1:    //    线路一抢单  快车
                                    handlerTimeStart.sendEmptyMessageDelayed(0, 30000);
                                    routeOneOrder();
                                    break;
                                case 4:       //    线路四抢单  专车
                                    handlerTimeStart.sendEmptyMessageDelayed(0, 30000);
                                    routeFourOrder();
                                    break;
                            }
                            break;
//                        ***************************************************
                        case 203:
                            teNearOrder.setVisibility(View.VISIBLE);
                            break;
                        case 206:
                            teNearOrder.setVisibility(View.VISIBLE);
                            showToast("坐标错误!");
                            break;
                        case 208:
                            showToast("车辆封停状态，无法接单!");
                            break;
                        case 209:
                            showToast("等待认证!");
                            break;
                        case 404:
                            showToast("请求失败!");
                            teNearOrder.setVisibility(View.VISIBLE);
                            break;
                        case 205:
                            //  推送订单1
                            if (datajj.size() > 0) {
                                String routeszz = datajj.get(0).getRoutes().toString().trim();
                                if (routeszz.equals(2 + "")) {// 班车
                                    teHavingOrders.setVisibility(View.VISIBLE);
                                    teHavingOrders.setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Intent inten12 = new Intent(MapFragment.this.getContext(), PushOrders.class);
                                            inten12.putExtra("mLatitude", mLatitude);
                                            inten12.putExtra("mLongitude", mLongitude);
                                            inten12.putExtra("isDingDanJX", isDingDanJX);
                                            inten12.putExtra("pushOrdersEntity", pushOrdersEntity);
                                            inten12.setAction("dingdanxianlu2");
                                            //让对话框消失
                                            isDingDanJX = true;
                                            teHavingOrders.setVisibility(View.GONE);
                                            startActivity(inten12);
                                        }
                                    });
                                    //推送订单二
                                } else if (routeszz.equals(1 + "")) {//快车
                                    String trim = datajj.get(0).getStatus().toString().trim();
                                    teHavingOrders.setVisibility(View.VISIBLE);
                                    teNearOrder.setVisibility(View.GONE);
                                    if (trim.equals("6")) {
                                        teHavingOrders.setOnClickListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                boolean serviceWork = isServiceWork(getActivity(), "com.fxsh168.server.QueryDistanceService");
                                                Intent intent3 = new Intent(getActivity(), NavQian.class);
                                                intent3.putExtra("pushOrdersEntity2", pushOrdersEntity);
                                                intent3.putExtra("isDingDanJXCH", isDingDanJX);
                                                intent3.setAction("btnRouteSchedul");
                                                intent3.putExtra("biao", "hjc");
                                                if (serviceWork) {
                                                    startActivity(intent3);
                                                    handlerGetOrder.removeCallbacksAndMessages(null);
                                                } else {
                                                    String trim1 = datajj.get(0).getId().toString().trim();
                                                    Intent intent = new Intent(getActivity(), QueryDistanceService.class);
                                                    intent.putExtra("ids", trim1);
                                                    getActivity().startService(intent);
                                                    startActivity(intent3);
                                                    handlerGetOrder.removeCallbacksAndMessages(null);
                                                }
                                            }
                                        });
                                    } else {
                                        teHavingOrders.setOnClickListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                Intent inten11 = new Intent(MapFragment.this.getContext(), PushOrders.class);
                                                inten11.putExtra("mLatitude", mLatitude);
                                                inten11.putExtra("mLongitude", mLongitude);
                                                inten11.putExtra("isDingDanJX", isDingDanJX);
                                                inten11.putExtra("pushOrdersEntity", pushOrdersEntity);
                                                inten11.setAction("dingdanxianlu1");
                                                isDingDanJX = true;
                                                //让对话框消失
                                                teHavingOrders.setVisibility(View.GONE);
                                                startActivity(inten11);
                                            }
                                        });
                                    }
                                }
                            }
                            break;
                    }

                }
            }
        });
    }

    //    时间计算
    Handler handlerTimeStart = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            liQiangOrder.setVisibility(View.GONE);
            teHavingOrders.setVisibility(View.GONE);
            isDingDanJX = false;
            //超时之后
            refuseOrderss();    //拒绝订单
            getOrderInfo();     //   获取订单
        }
    };

    /**
     * 30秒时候自动取消订单
     */
    public void refuseOrderss() {
        if (idjjs == null){
            return;
        }
        if (idjjs.size() == 0){
            return;
        }
        String idjjcur6 = idjjs.get(idjjs.size() - 1);
        OkHttpUtils.post().addParams("phone", mPhoneMap).addParams("token", tokenMap)
                .addParams("id", idjjcur6).url(Constant.ORDERFUSEREQUESTPATHSS).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        showToast("连接不上服务器!");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            RegiYZMCG regiYZMCG = new Gson().fromJson(response, RegiYZMCG.class);
                            String code = regiYZMCG.getCode().trim();
                            if (code.equals(200 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(201 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(202 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(203 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
//                                showToast("来得太慢，订单没了，请加快手速!");
                            }
                        }
                    }
                });
    }
    //    线路四抢单
    public void routeFourOrder() {
        //线路4，抢单
        liQiangOrder.setVisibility(View.VISIBLE);
        teHavingOrders.setVisibility(View.GONE);
        teNearOrder.setVisibility(View.GONE);
        playVoce(3, getActivity());
        mStartPlace.setText(datajj.get(0).getAddresses().toString().trim());
        mEndPlace.setText(datajj.get(0).getDown().toString().trim());
        if (datajj.size() > 0) {
            idjjs.clear();
            for (int i = 0; i < datajj.size(); i++) {
                String idjj = datajj.get(i).getId().toString().trim();
                idjjs.add(idjj);
            }
        }
        imaCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                liQiangOrder.setVisibility(View.GONE);
                teHavingOrders.setVisibility(View.GONE);
                isDingDanJX = false;
                refuseOrder(idjjs.get(0));    //拒绝订单
            }
        });

        mQiangDan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                liQiangOrder.setVisibility(View.GONE);
                teHavingOrders.setVisibility(View.GONE);
                agreeOrders(idjjs.get(0));      //接受订单
            }
        });
        isDingDanJX = true;
    }

    //    线路一抢单
    public void routeOneOrder() {
        liQiangOrder.setVisibility(View.VISIBLE);
        teHavingOrders.setVisibility(View.GONE);
        teNearOrder.setVisibility(View.GONE);
        playVoce(3, getActivity());
        mStartPlace.setText(datajj.get(0).getAddresses().toString().trim());
        mEndPlace.setText(datajj.get(0).getDown().toString().trim());
        if (datajj.size() > 0) {
            idjjs.clear();
            for (int i = 0; i < datajj.size(); i++) {
                String idjj = datajj.get(i).getId().toString().trim();
                idjjs.add(idjj);
            }
        }
        imaCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                liQiangOrder.setVisibility(View.GONE);
                teHavingOrders.setVisibility(View.GONE);
                isDingDanJX = false;
                refuseOrder(idjjs.get(0));    //拒绝订单
            }
        });
        mQiangDan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                liQiangOrder.setVisibility(View.GONE);
                teHavingOrders.setVisibility(View.GONE);
                agreeOrders(idjjs.get(0));      //接受订单
            }
        });
        isDingDanJX = true;
    }


    //       拒绝所有订单和接单
    public void refuseOrder(String orderId) {
        OkHttpUtils.post().addParams("phone", mPhoneMap).addParams("token", tokenMap)
                .addParams("id", orderId).url(Constant.ORDERFUSEREQUESTPATH).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        showToast("连接不上服务器!");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            RegiYZMCG regiYZMCG = new Gson().fromJson(response, RegiYZMCG.class);
                            String code = regiYZMCG.getCode().trim();
                            if (code.equals(200 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(201 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(202 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                            } else if (code.equals(203 + "")) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
//                                showToast("来得太慢，订单没了，请加快手速!");
                            }
                        }
                    }
                });
    }

    private AlertDialog dialogSJYJD;

    //    接单
    public void agreeOrders(String orderId) {
        OkHttpUtils.post().addParams("phone", mPhoneMap).addParams("token", tokenMap)
                .addParams("id", orderId).url(Constant.ORDERECIVEREQUESTPATH)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    RegiYZMCG regiYZMCG = new Gson().fromJson(response, RegiYZMCG.class);
                    String code = regiYZMCG.getCode().trim();
                    if (code.equals(200 + "")) {
                        getActivity().getSharedPreferences(Constant.PLACED, Context.MODE_PRIVATE).edit().putBoolean("finish",false).commit();
                        Intent inten = new Intent(MapFragment.this.getContext(), PushOrders.class);
                        inten.putExtra("mLatitude", mLatitude);
                        inten.putExtra("mLongitude", mLongitude);
                        inten.putExtra("isDingDanJX", isDingDanJX);
                        inten.putExtra("pushOrdersEntity", pushOrdersEntity);
                        inten.setAction("dingdanxianlu1");
                        isDingDanJX = true;
                        startActivity(inten);
                    } else if (code.equals(201 + "")) {
                        isDingDanJX = false;
                        handlerGetOrder.sendEmptyMessage(200);
                    } else if (code.equals(202 + "")) {
                        isDingDanJX = false;
                        handlerGetOrder.sendEmptyMessage(200);
                    } else if (code.equals(203 + "")) {
                        Log.e("code", "接单失败!");
                        isDingDanJX = false;
                        handlerGetOrder.sendEmptyMessage(200);
                    } else if (code.equals(222 + "")) {
                        Toast.makeText(MapFragment.this.getActivity(), "来得太慢，订单没了，请加快手速!", Toast.LENGTH_SHORT).show();
                        AlertDialog.Builder builderbeijie = new AlertDialog.Builder(MapFragment.this.getActivity());
                        View viewbeijie = LayoutInflater.from(MapFragment.this.getActivity()).inflate(R.layout.dingdanbeijiedialog_layout, null);
                        builderbeijie.setView(viewbeijie);
                        TextView btnOkbeijie = (TextView) viewbeijie.findViewById(R.id.btnOKSJYJD);
                        btnOkbeijie.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                isDingDanJX = false;
                                handlerGetOrder.sendEmptyMessageDelayed(200, 2000);
                                //让对话框消失
                                dialogSJYJD.dismiss();
                            }
                        });
                        dialogSJYJD = builderbeijie.create();
                        dialogSJYJD.setCanceledOnTouchOutside(false);
                        dialogSJYJD.show();

                        WindowManager mSJYJD = getActivity().getWindowManager();
                        Display dSJYJD = mSJYJD.getDefaultDisplay(); // 获取屏幕宽、高用
                        WindowManager.LayoutParams pSJYJD = dialogSJYJD.getWindow().getAttributes(); // 获取对话框当前的参数值
                        pSJYJD.height = (int) (dSJYJD.getHeight() * 0.23); // 高度设置为屏幕的0.6
                        pSJYJD.width = (int) (dSJYJD.getWidth() * 0.75); // 宽度设置为屏幕的0.95
                        dialogSJYJD.getWindow().setBackgroundDrawableResource(R.drawable.shapedingdan);
                        dialogSJYJD.getWindow().setAttributes(pSJYJD);
                        isDingDanJX = false;
                        handlerGetOrder.sendEmptyMessageDelayed(200, 10000);
                    }
                }
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();
        //开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        myOrientationListener.start();
    }


    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
        isDingDanJX = false; //获得焦点时进行数据请求
        Message message = new Message();
        message.what = 200;
        Bundle bundle = new Bundle();
        bundle.putDouble("mLatitude", mLatitude);
        bundle.putDouble("mLongitude", mLongitude);
        message.setData(bundle);
        if (getActivity().getSharedPreferences(Constant.PLACED, Context.MODE_PRIVATE).getBoolean("finish",false)){//判断订单是否完成
            teHavingOrders.setVisibility(View.GONE);//退出来的时候把这个隐藏了
        }
        handlerGetOrder.sendMessageDelayed(message, 2000);
    }


    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        handlerTimeStart.removeCallbacksAndMessages(null);
//        //停止定位
//        mBaiduMap.setMyLocationEnabled(false);
//        mLocationClient.stop();
//        //停止方向传感器
//        isDingDanJX = true;//不可见时不进行数据请求
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        myOrientationListener.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        handlerGetOrder.removeCallbacksAndMessages(null);
        handlerTimeStart.removeCallbacksAndMessages(null);
    }


    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}
